<template>
    <div class="box-card box-minheight">
        <div class="card-header">
            <span>{{ curRouteName }}</span>
        </div>
        <div class="box-content">
            <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                <el-form-item label="分类名称">
                    <el-select v-model="searchForm.className" placeholder="请选择分类名称" clearable filterable>
                        <el-option label="源" value="0" />
                        <el-option label="储" value="1" />
                        <el-option label="荷" value="2" />
                        <el-option label="电网参数" value="3" />
                        <el-option label="发电机组" value="4" />
                        <el-option label="负荷监测" value="5" />
                        <el-option label="储能设备" value="6" />
                        <el-option label="太阳能光伏" value="7" />
                        <el-option label="风力发电" value="8" />
                        <el-option label="逆变器监测" value="9" />
                        <el-option label="电表" value="10" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备名称">
                    <el-select v-model="searchForm.deviceName" placeholder="请选择设备名称" clearable filterable>
                        <el-option label="1号电表" value="0" />
                        <el-option label="2号逆变器" value="1" />
                        <el-option label="3号电表" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备型号">
                    <el-select v-model="searchForm.deviceModel" placeholder="请选择设备型号" clearable filterable>
                        <el-option label="A001" value="0" />
                        <el-option label="A002" value="1" />
                        <el-option label="A003" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备厂家">
                    <el-select v-model="searchForm.deviceFactory" placeholder="请选择设备厂家" clearable filterable>
                        <el-option label="F001" value="0" />
                        <el-option label="F002" value="1" />
                        <el-option label="F003" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" size="default" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
            <div style="margin: 10px 0px;">
                <el-button type="primary" icon="Plus" @click="showDrawer('add')">新增</el-button>
                <el-button type="primary" icon="Upload" @click="handleImport">导入</el-button>
                <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
                <el-button type="danger" icon="Delete" @click="handleBatchDelete">批量删除</el-button>
            </div>
            <el-table :data="devices" style="width: 100%" @selection-change="selectChange" border :height="tableHeight">
                <el-table-column type="selection"></el-table-column>
                <el-table-column prop="category" label="分类名称"></el-table-column>
                <el-table-column prop="name" label="设备名称"></el-table-column>
                <el-table-column prop="manufacturer" label="厂家"></el-table-column>
                <el-table-column prop="model" label="设备型号"></el-table-column>
                <!-- <el-table-column prop="controllerType" label="控制器类型"></el-table-column> -->
                <el-table-column label="操作" width="450">
                    <template #default="{ row }">
                        <el-button type="primary" icon="Edit" size="small" @click="showDrawer('edit', row)">编辑</el-button>
                        <!-- <el-button type="primary" size="small" @click="handleSignal(row)">信号添加</el-button> -->
                        <el-button type="primary" size="small" @click="handleSignal2(row)">信号添加</el-button>
                        <el-button type="primary" size="small" icon="VideoCamera"
                            @click="handleMonitor(row)">信号配置</el-button>
                        <el-popconfirm :title="`你确定要删除${row.category}的${row.name}?`" width="260px"
                            @confirm="handleDelete(row)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination class="mt10" v-model:current-page="pageNo" v-model:page-size="pageSize"
                :page-sizes="[5, 7, 9, 11]" :background="true" layout="prev, pager, next, jumper,->,sizes,total"
                :total="total" @current-change="getTableData" @size-change="handler" />
        </div>
    </div>
    <!-- 编辑 -->
    <el-drawer v-model="drawerVisible" :size="drawerSize">
        <template #header>
            <h4>{{ drawerTitle }}</h4>
        </template>
        <template #default>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="分类名称" prop="category">
                    <!-- <el-input v-model="form.category"></el-input> -->
                    <el-select v-model="form.category" placeholder="请选择分类名称" clearable filterable style="width:100%">
                        <el-option label="源" value="0" />
                        <el-option label="储" value="1" />
                        <el-option label="荷" value="2" />
                        <!-- <el-option label="电网参数" value="3" />
                        <el-option label="发电机组" value="4" />
                        <el-option label="负荷监测" value="5" />
                        <el-option label="储能设备" value="6" />
                        <el-option label="太阳能光伏" value="7" />
                        <el-option label="风力发电" value="8" />
                        <el-option label="逆变器监测" value="9" />
                        <el-option label="电表" value="10" /> -->
                    </el-select>

                </el-form-item>
                <el-form-item label="设备名称" prop="name">
                    <!-- <el-input v-model="form.name"></el-input> -->
                    <el-select v-model="form.name" placeholder="请选择设备名称" clearable filterable style="width:100%">
                        <el-option label="1号电表" value="0" />
                        <el-option label="2号逆变器" value="1" />
                        <el-option label="3号电表" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="厂家" prop="manufacturer">
                    <el-input v-model="form.manufacturer"></el-input>
                </el-form-item>
                <el-form-item label="设备型号" prop="model">
                    <el-input v-model="form.model"></el-input>
                </el-form-item>

                <!-- <el-form-item label="控制器类型" prop="controllerType">
                    <el-input v-model="form.controllerType"></el-input>
                </el-form-item> -->
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button type="primary" @click="handleSubmit">保存</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </template>
    </el-drawer>

    <!-- 信号 -->
    <SignalForm ref="signalForm" :signalVisible="signalVisible" @closeSignal="closeSignal"></SignalForm>
    <!-- 信号 -->
    <SignalForm2 ref="signalForm2" :signalVisible2="signalVisible2" @closeSignal2="closeSignal2"></SignalForm2>
    <!-- 监控点 -->
    <MonitorForm ref="monitorForm" :monitorVisible="monitorVisible" @closeMonitor="closeMonitor"></MonitorForm>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { ref, computed, reactive, nextTick, onMounted, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import SignalForm from '@/views/gatherOrder/codelibrary/signalForm.vue'
import MonitorForm from '@/views/gatherOrder/codelibrary/monitorForm.vue'
import SignalForm2 from '@/views/gatherOrder/codelibrary/signalForm2.vue'


//获取路由对象
let $route = useRoute()
// 计算出当前路由名称
let curRouteName = computed(() => {
    return $route.matched[$route.matched.length - 1].meta.title
})
const searchFormRef = ref<FormInstance | null>(null)
const searchForm = reactive({
    className: '0',
    deviceName: '2',
    deviceModel: '0',
    deviceFactory: '2',
})
const handleSearch = () => {
    console.log('submit!')
}
//重置按钮
const handleReset = () => {
}

interface Device {
    id: number;
    category: string;
    name: string;
    model: string;
    manufacturer: string;
    // controllerType: string;
}
//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<Device[]>([]);
const devices = ref<Device[]>([
    {
        id: 1,
        category: '源',
        name: '光伏发电机1号',
        manufacturer: '1号厂家',
        model: 'A001',
        // controllerType: 'YD',
    },
    {
        id: 2,
        category: '储',
        name: '1号储能设备',
        manufacturer: '2号厂家',
        model: 'B001',
        // controllerType: 'YD',
    },
    // 可以添加更多的设备类型数据
]);
//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(5);
//用户总个数
let total = ref<number>(0);

//组件挂载完毕
onMounted(() => {
    getTableData();
    calculateTableHeight();
    window.addEventListener('resize', handleResize);
});
onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
})
const getTableData = async (pager = 1) => {
    //收集当前页码
    pageNo.value = pager;
    // let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyword.value);
    // if (result.code == 200) {
    //     total.value = result.data.total;
    //     userArr.value = result.data.records;
    // }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
    getTableData();
}

const tableHeight = ref(0); // 表格高度
// 计算表格高度的函数
const calculateTableHeight = () => {
    const windowHeight = window.innerHeight - 180; // 获取窗口高度
    const tableHeaderHeight = 40; // 表格头部高度
    const tablePaginationHeight = 60; // 表格分页高度
    const padding = 20; // 上下边距
    tableHeight.value = windowHeight - tableHeaderHeight - tablePaginationHeight - padding;
};

// 监听窗口大小变化，动态计算表格高度
const handleResize = () => {
    calculateTableHeight();
};



const drawerVisible = ref(false);
const drawerTitle = ref('');
const drawerSize = ref('600');
//获取form组件实例
let formRef = ref<any>();
let signalForm = ref<any>();
let signalForm2 = ref<any>();
let monitorForm = ref<any>();

const form = reactive({
    id: 0,
    category: '',
    name: '',
    model: '',
    manufacturer: '',
    controllerType: '',
});
const rules = reactive<FormRules<Device>>({
    category: [{ required: true, message: '请选择分类名称', trigger: 'blur' }],
    name: [{ required: true, message: '请选择设备名称', trigger: 'blur' }],
    model: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
    manufacturer: [{ required: true, message: '请输入厂家', trigger: 'blur' }],
    // controllerType: [{ required: true, message: '请输入控制器类型', trigger: 'blur' }],
});

function showDrawer(type: 'add' | 'edit', row?: Device) {
    handleClear()
    if (type === 'add') {
        drawerTitle.value = '新增';
        form.id = 0;
        form.category = '';
        form.name = '';
        form.model = '';
        form.manufacturer = '';
        form.controllerType = '';
    } else if (type === 'edit' && row) {
        console.log('bj', row)
        drawerTitle.value = '编辑';
        form.id = row.id;
        form.category = row.category
        form.name = row.name
        form.model = row.model
        form.manufacturer = row.manufacturer
        form.controllerType = row.controllerType

    }
    console.log('type', type)
    console.log('form', form)
    drawerVisible.value = true;
}

const handleSubmit = () => {
    (formRef.value as any).validate((valid: boolean) => {
        if (valid) {
            if (form.id === 0) {
                // 新增设备类型
                const newDeviceType: Device = {
                    id: devices.value.length + 1,
                    category: form.category,
                    name: form.name,
                    model: form.model,
                    manufacturer: form.manufacturer,
                    controllerType: form.controllerType
                };
                devices.value.push(newDeviceType);
                ElMessage({
                    message: '新增成功！',
                    type: 'success',
                })
            } else {
                // 编辑设备类型
                const index = devices.value.findIndex((item) => item.id === form.value.id);
                if (index !== -1) {
                    devices.value[index].category = form.category;
                    devices.value[index].name = form.name;
                    devices.value[index].model = form.model;
                    devices.value[index].manufacturer = form.manufacturer;
                    devices.value[index].controllerType = form.controllerType;
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                }
            }
            drawerVisible.value = false;
        } else {
            return false;
        }
    });
}
const handleClear = () => {
    nextTick(() => {
        formRef.value?.clearValidate()
    })
}

function handleCancel() {
    drawerVisible.value = false;
}

function handleDelete(row: Device) {
    const index = devices.value.findIndex((item) => item.id === row.id);
    if (index !== -1) {
        devices.value.splice(index, 1);
        ElMessage.success('删除成功');
    }
}

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
    selectIdArr.value = value;
}

function handleBatchDelete() {
    // const selectedRows = (this.$refs.table as any).getSelection();
    if (selectIdArr.value.length === 0) {
        ElMessage.warning('请先选择要删除的设备类型');
        return;
    }
    const ids = selectIdArr.value.map((item: Device) => item.id);
    devices.value = devices.value.filter((item) => !ids.includes(item.id));
    ElMessage.success('删除成功');
}

const handleImport = () => {
    // 处理导入逻辑
}

const handleExport = () => {
    // 处理导出逻辑
}
const signalVisible = ref(false)
const handleSignal = () => {
    signalVisible.value = true
}
const closeSignal = (v: any) => {
    // console.log('vvv', v)
    signalVisible.value = v
}

const signalVisible2 = ref(false)
const handleSignal2 = () => {
    signalVisible2.value = true
}
const closeSignal2 = (v: any) => {
    // console.log('vvv', v)
    signalVisible2.value = v
}



const monitorVisible = ref(false)
const handleMonitor = () => {
    monitorVisible.value = true
}
const closeMonitor = (v: any) => {
    // console.log('vvv', v)
    monitorVisible.value = v
}



</script>

<style scoped lang="scss">
.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
    height: 100%;
}
</style>